package com.rjkj.medicalwaste.ui.collect

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.CodeType
import com.rjkj.medicalwaste.databinding.FragmentCollectScanBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.viewmodels.CollectScanViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import com.rjkj.zxinglibrary.zxing.android.CaptureActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class CollectScanFragment : BaseFragment<FragmentCollectScanBinding>() {
    private val viewModel: CollectScanViewModel by viewModels()
    private val userViewModel : UserViewModel by activityViewModels{
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private lateinit var startActivity: ActivityResultLauncher<Intent>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            val resultCode = it.resultCode
            if(resultCode == Activity.RESULT_OK){
                val data = it.data?.extras?.getString("codedContent")?:""
                Log.e(TAG, "onCreate: ${resultCode}+${data}" )
                doScanCode(data)
            }else{
                showTip("扫码失败")
            }
        }

    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        val binding = FragmentCollectScanBinding.inflate(inflater, container, false)
        binding.scanData = viewModel
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        initKeyEvent()
        return binding.root
    }

    override fun dealCustomScanData(data: String) {
        super.dealCustomScanData(data)
        doScanCode(data)
    }
    override fun onSubscribeUi(binding: FragmentCollectScanBinding) {
        initTip(viewModel)
        binding.pic.setOnClickListener {
            scanWithCustomUI()
//            val intent = Intent(requireContext(), CaptureActivity::class.java)
//            startActivity.launch(intent)
        }
        binding.tvDepartment.setOnClickListener {
            scanWithCustomUI()
        }
        binding.tvNurse.setOnClickListener {
            scanWithCustomUI()
        }
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
                viewLifecycleOwner, {
            doScanCode(it)
        })
    }

    private fun doScanCode(s: String) {
        Log.e(TAG, "FragmentCollectScanBinding: $s")
        checkCode(s).let { type ->
            if (type == CodeType.Department) {
                userViewModel.checkLogin(s).observe(viewLifecycleOwner, { user ->
                    if (user != null) {
                        Log.e(TAG, "onSubscribeUi: ${user.toString()}")
                        viewModel.department.value = user
                    } else {
                        viewModel.department.value = null
                        viewModel.tips.value = "未查询到该用户！"
                    }
                })
            } else if (type == CodeType.Nurser) {
                if (viewModel.department.value != null) {
                    userViewModel.checkLogin(s).observe(viewLifecycleOwner, { user ->
                        if (user != null) {
                            Log.e(TAG, "onSubscribeUi: ${user.toString()}")
                            viewModel.nurse.value = user
                            viewModel.tips.value = "登录成功"
                            userViewModel.nurseUser.value = viewModel.nurse.value
                            userViewModel.departmentUser.value = viewModel.department.value
                            Log.e(TAG, "userViewModel: ${userViewModel.toString()}")
                            lifecycleScope.launch {
                                delay(250L)
                                findNavController().navigate(R.id.action_collectScanFragment_to_collectMainFragment)
                            }
                        } else {
                            viewModel.nurse.value = null
                            viewModel.tips.value = "未查询到该用户！"
                        }
                    })
                } else {
                    showTip("请先扫描科室二维码")
                }
            } else {
                showTip("请勿扫描${type.alias}")
            }
        }
    }


}